<template>
  <div class="container">
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button
          :disabled="msgcodeFlag"
          @click="sendMessage"
          size="small"
          round
          type="danger"
          >{{ msgCodeContent }}</van-button
        >
      </template>
    </van-field>
    <van-button @click="handleNext" type="danger" :disabled="!btnNextFlag" round block
      >下一步</van-button
    >
  </div>
</template>

<script lang="ts" setup>
import { useLoginStore } from '@/stores/login'
import { dosendmsgcode, docheckcode } from '@/api/login'
import { storeToRefs } from 'pinia'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { Notify } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const loginStore = useLoginStore()
const { tel } = storeToRefs(loginStore)
let _time = 0
let timer: number | undefined = undefined
const sms = ref('')
const btnNextFlag = computed(() => /^\d{5}$/.test(sms.value))
const msgCodeContent = ref('发送验证码')
const msgcodeFlag = computed(() => msgCodeContent.value !== '发送验证码')

// 组件销毁之前保存验证码按钮可用的剩余时间（节省公司的钱）
const saveRemainTime = () => {
  if (_time !== 0) {
    // 本地保存验证码剩余时间，再次进入页面的时候跟本地时间对比是否跑完
    localStorage.setItem('time', new Date().getTime() + '_' + _time)
  }
}

// 如果从外部传入了time就表示刷新了页面，还有剩余时间没有跑完
const countdown = (time: number = 60) => {
  // 开启之前先清理,保险操作
  clearInterval(timer)
  // 发送验证码60s后再次发送, *1 字符串变数字
  _time = time
  timer = setInterval(() => {
    msgCodeContent.value = --_time + 's 后再次发送'
    if (_time === 0) {
      msgCodeContent.value = '发送验证码'
      clearInterval(timer)
      // 倒计时完毕清空保存的time剩余值
      localStorage.removeItem('time')
    }
  }, 1000)
}

const sendMessage = () => {
  if (!tel.value) return false
  countdown()
  tel.value &&
    dosendmsgcode({ tel: tel.value })
      .then((res: any) => {
        if (res.code === '200') {
          Notify({ type: 'danger', message: '验证码已发送' })
        } else {
          Notify({ type: 'danger', message: res.message })
        }
      })
      .catch((error) => {
        console.log(error)
      })
}

// 验证验证码是否正确
const handleNext = () => {
  docheckcode({
    tel: tel.value,
    telcode: sms.value,
  })
    .then((res) => {
      console.log(res)
      // 验证码无效，提示错误信息
      if ((res as any).code === '10007') {
        Notify({ type: 'danger', message: (res as any).message })
      } else {
        router.push('/register/step3')
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

onBeforeUnmount(() => {
  // 页面意外关闭，清除timer
  clearInterval(timer)
  saveRemainTime()
})

onMounted(() => {
  if (localStorage.getItem('time')) {
    const localTime = (localStorage.getItem('time') as string).split('_')
    const runTime = new Date().getTime() - Number(localTime[0])
    if (Math.round(runTime / 1000) < Number(localTime[1])) {
      countdown(Number(localTime[1]) - Math.round(runTime / 1000))
    }
  }
  window.onbeforeunload = saveRemainTime.bind(this)
})
</script>

<style lang="scss" scoped>
.container {
  padding: 50px 30px;
  background: #fff;
  box-sizing: border-box;
  .input {
    margin-bottom: 100px;
  }
}
</style>
